const Koa = require('koa')
const bodyparser = require('koa-bodyparser')
const requestContext = require('./middlewares/requestContext')
const errorHandler = require('./middlewares/errorHandler')
const notFound = require('./middlewares/notFoundHandler')
const { Init } = require('./care/init')
const serve = require('koa-static')
require('dotenv').config()
require('./utils/relevance')

const port = 30
const app = new Koa()
app.use(
  serve(__dirname + '/public', {
    extensions: ['html'],
    gzip: true,
  }),
)

app.use(requestContext) // 第一层：请求上下文
app.use(errorHandler) // 第二层：错误处理
app.use(bodyparser())

// 批量注册路由app
Init.init(app)
// 404处理（必须最后）
app.use(notFound)

// 监听未匹配路由日志
app.on('routeWarn', ({ message, ctx }) => {
  console.warn(`[ROUTE WARN] ${message}`, {
    method: ctx.method,
    path: ctx.path,
    ip: ctx.ip,
  })
})

app.listen(port, () => {
  console.log(`koa server running at http://localhost:${port}`)
})
